using Infrastructure.Attribute;
using Infrastructure.Extensions;
using JTZY.Model.Batch.Dto;
using JTZY.Model.Batch;
using JTZY.Repository;
using JTZY.Service.Batch.IBatchService;
using JTZY.Common;
using static JTZY.Common.GlobalEnumVars;
using JTZY.Service.Product.IProductService;
using JTZY.Service.Business.IBusinessService;
using JTZY.Model.Business;
using JTZY.Model.Product;

namespace JTZY.Service.Batch
{
    /// <summary>
    /// 批量发货Service业务层处理
    /// </summary>
    [AppService(ServiceType = typeof(IBatchshipService), ServiceLifetime = LifeTime.Transient)]
    public class BatchshipService : BaseService<Batchship>, IBatchshipService
    {
        private readonly IBatchshipitemService _batchshipitemService;
        private readonly IBatchshipdetailService _batchshipdetailService;
        private readonly IProdinfoService _prodinfoService;
        private readonly IStockFlowItemService _stockFlowItemService;
        public BatchshipService(IBatchshipdetailService batchshipdetailService
            , IProdinfoService prodinfoService
            , IStockFlowItemService stockFlowItemService
            , IBatchshipitemService batchshipitemService)
        {
            _batchshipitemService = batchshipitemService;
            _batchshipdetailService = batchshipdetailService;
            _prodinfoService = prodinfoService;
            _stockFlowItemService = stockFlowItemService;
        }

        /// <summary>
        /// 查询批量发货列表
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        public PagedInfo<BatchshipDto> GetList(BatchshipQueryDto parm)
        {
            var predicate = QueryExp(parm);

            var response = Queryable()
                .Includes(x => x.BatchshipitemNav) //填充子对象
                .Where(predicate.ToExpression()).OrderByDescending(it => new { it.CreateTime })
                .ToPage<Batchship, BatchshipDto>(parm);

            return response;
        }


        /// <summary>
        /// 获取详情
        /// </summary>
        /// <param name="OrderId"></param>
        /// <returns></returns>
        public Batchship GetInfo(string OrderId)
        {
            var response = Queryable()
                .Includes(x => x.BatchshipitemNav) //填充子对象
                .Where(x => x.OrderId == OrderId)
                .First();

            return response;
        }

        /// <summary>
        /// 添加批量发货
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public Batchship AddBatchship(Batchship model)
        {
            return Context.InsertNav(model).Include(s1 => s1.BatchshipitemNav).ExecuteReturnEntity();
        }

        /// <summary>
        ///  批量发货
        /// </summary>
        /// <returns></returns>
        public WebApiCallBack ToAdd(List<Batchshipitem> items, List<Batchshipdetail> details, long userId) 
        {
            var jm = new WebApiCallBack();
            var orderId  = CommonHelper.GetSerialNumberType((int)SerialNumberType.批量发货订单编号);
            foreach (var item in items)
            {
                item.OrderId = orderId;
            }

            foreach (var detail in details)
            {
                detail.OrderId = orderId;
            }

            var batchShip = new Batchship();
            batchShip.OrderId = orderId;
            batchShip.CreateTime = DateTime.Now;
            batchShip.UserId = userId;
            batchShip.Status = 0;//发货
            batchShip.Nums = details.Count;

            var res=UseTran(() => {
                _batchshipitemService.InsertRange(items);
                Insert(batchShip);
                _batchshipdetailService.Insert(details);

                //更新出库
                foreach (var item in details)
                {
                    _prodinfoService.Update(p => p.SnCode == item.SnCode, p => new Prodinfo { Status = 2 });

                    var prod=items.Where(i => i.ProductId == item.ProductId).First();
                    _stockFlowItemService.Insert(new StockFlowItem
                    {
                        SheetNo = item.AftersalesId,
                        DbNo = "-",
                        ProductId = item.ProductId,
                        OrderType = 4,
                        SnCode = item.SnCode,
                        UserId = userId,
                        Price = item.Price,
                        CreateTime = batchShip.CreateTime

                    });
                }
               // _prodinfoService.Queryable().Where(p=>p.UserId== userId).ToList();

            });
            jm.status = res.IsSuccess;
            jm.msg = res.ErrorMessage;
            jm.data = batchShip;
            return jm;
        }

        /// <summary>
        /// 修改批量发货
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int UpdateBatchship(Batchship model)
        {
            return Context.UpdateNav(model).Include(z1 => z1.BatchshipitemNav).ExecuteCommand() ? 1 : 0;
        }

        /// <summary>
        /// 查询导出表达式
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        private static Expressionable<Batchship> QueryExp(BatchshipQueryDto parm)
        {
            var predicate = Expressionable.Create<Batchship>();
            predicate = predicate.And(it=>it.UserId == parm.UserId);
            predicate = predicate.AndIF(parm.BeginCreateTime == null, it => it.CreateTime >= DateTime.Now.AddDays(-365).ToShortDateString().ParseToDateTime());
            predicate = predicate.AndIF(parm.BeginCreateTime != null, it => it.CreateTime >= parm.BeginCreateTime);
            predicate = predicate.AndIF(parm.EndCreateTime != null, it => it.CreateTime < parm.EndCreateTime.Value.AddDays(1));
            return predicate;
        }
    }
}